<template>
  <van-popup
    v-model="showSelectBackgroundFlag"
    position='bottom'
    :round="true"
    get-container="body"
    :duration="0.2"
    @close="handleClose">
      <div class="background-container">
        <!-- 头部导航栏 -->
        <div class="header-content">
          <van-search
            v-model="selection_model.model_name"
            show-action
            label="搜索"
            placeholder="请输入车系名称（例如：雅阁）"
            @search="onSearch"
            class="search-model"
          >
            <template #action>
              <div class="search-btn" @click="onSearch">搜索</div>
            </template>
          </van-search>
        </div>
        <!-- 汽车品牌选择 -->
        <template v-if="step === 0">
          <van-tabs
            v-model="searchTabIndex"
            :line-width="0"
            :line-height="20"
            title-active-color="#8773f9"
            @change="changeBrand">
            <van-tab
              v-for="(item, index) in brand_letter"
              :key="index"
              :title="item"
              :title-style="{
                padding: '10px',
                border: '1px solid #000',
                height: '20px',
                'borderRadius': '11px',
                'marginRight': '8px',
              }"></van-tab>
          </van-tabs>
          
          <div class="brand-content">
            <div v-if="brandListData && brandListData.length> 0" class="brand_item">
              <van-grid
                :border="true" 
                icon-size="40"
                :gutter="8"
                square>
                <van-grid-item
                  v-for="item in brandListData"
                  :key="item.id"
                  :icon="item.brand_img"
                  :text="item.brand_name"
                  @click="handleBrandItem(item)" />
              </van-grid>
            </div>
            <div v-else style="text-align: center;">
              <van-empty description="暂无数据" />
            </div>
          </div>
        </template>

        <!-- 汽车车系选择 -->
        <template v-else-if="step === 1">
          
          <div class="series-nav">
            <div class="back-btn" @click="handleStep">
              <van-icon name="arrow-left" color="#fff" class="back-icon" />
            </div>
            <van-tabs
              v-model="carSeriesTypeIndex"
              :line-width="0"
              :scrollspy="true"
              :line-height="20"
              title-active-color="#8773f9"
              @change="changeCarSeries"
              style="flex: 1;">
              <van-tab
                v-for="(item, index) in carSeriesList"
                :key="item.id"
                :title="item.name"
                :title-style="{
                  padding: '10px 10px',
                  border: '1px solid #000',
                  height: '20px',
                  'borderRadius': '11px',
                  'marginRight': '8px',
                  'maxWidth': '60px'
                }"></van-tab>
            </van-tabs>
          </div>
          
          <div class="brand-content">
            <div v-if="carSeriesList[carSeriesTypeIndex] && carSeriesList[carSeriesTypeIndex].seriesList.length> 0" class="brand_item">
              <van-grid
                :border="true" 
                icon-size="40"
                :gutter="8"
                square>
                <van-grid-item
                  v-for="item in carSeriesList[carSeriesTypeIndex].seriesList"
                  :key="item.id"
                  :icon="item.series_img"
                  :text="item.series_name"
                  @click="handleSeriesItem(item)" />
              </van-grid>
            </div>
            <div v-else style="text-align: center;">
              <van-empty description="暂无数据" />
            </div>
          </div>
        </template>

        <!-- 汽车车系年份选择 -->
        <template v-else-if="step === 2">
          
          <div class="series-nav">
            <div class="back-btn" @click="handleStep">
              <van-icon name="arrow-left" color="#fff" class="back-icon" />
            </div>
            <van-tabs
              v-model="modelYearIndex"
              :line-width="0"
              :scrollspy="true"
              :line-height="20"
              title-active-color="#8773f9"
              style="flex: 1;">
              <van-tab
                v-for="(item, index) in carModelListData"
                :key="index"
                :title="item.model_year"
                :title-style="{
                  padding: '10px 10px',
                  border: '1px solid #000',
                  height: '20px',
                  'borderRadius': '11px',
                  'marginRight': '8px',
                  'maxWidth': '60px'
                }"></van-tab>
            </van-tabs>
          </div>
          
          <div class="brand-content">
            <div v-if="carModelListData[modelYearIndex] && carModelListData[modelYearIndex].listData.length> 0" class="brand_item">
              <van-collapse v-model="activeModelColorName" accordion>
                <van-collapse-item
                  v-for="(item, index) in carModelListData[modelYearIndex].listData"
                  :key="item.id"
                  :title="item.model_name"
                  :name="index">
                  <div class="collapse-content">
                    <div class="model-image">
                      <van-image
                        width="80"
                        height="80"
                        radius="6px"
                        fit="contain"
                        :src="item.model_img"
                      />
                    </div>

                    <div class="model-list-item">
                      <div
                        v-for="s_item in item.carModelList"
                        :key="s_item.id"
                        class="list-item"
                        :style="{
                          'background': s_item.model_item_color
                        }"
                        @click="setPaster(s_item)"
                        >
                        <div class="list-item-name">{{ s_item.model_item_color_name }}</div>
                      </div>
                    </div>

                  </div>
                </van-collapse-item>
              </van-collapse>
            </div>
            <div v-else style="text-align: center;">
              <van-empty description="暂无数据" />
            </div>
          </div>
        </template>
      </div>
    </van-popup>
</template>

<script>
import { allCarBrandListData, allCarSeriesByBrandId, allCarModelListBySeriesId } from '@/utils/api'
export default {
  data() {
    return {
      step: 0,
      active: 0,
      searchTabIndex: 0, // 品牌
      carSeriesTypeIndex: 0, // 车系
      modelYearIndex: 0, // 年份
      activeModelColorName: 0, // 颜色
      searchBrand: {
        brand_name: '',
        brand_letter: '',
        is_hot: '1'
      },
      selection_model: {
        brand_id: '',
        series_id: '',
        model_name: ''
      },
      brandListData: [], // 品牌
      carSeriesList: [], // 车系
      carModelListData: [], // 车系型号
      showSelectBackgroundFlag: false,
      search_model: '',
      brand_letter: [ '热门', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ],
    };
  },

  watch: {
    '$store.state.design.currentSelectionType': {
      immediate: true,
      handler(val, oldVal) {
        const footerContainerEl = document.querySelector('#footer-container');
        if (val === 'background') {
          footerContainerEl.style.zIndex = '999';
          this.showSelectBackgroundFlag = !this.showSelectBackgroundFlag;
        } else if (oldVal === 'background'){
          this.showSelectBackgroundFlag = false;
        }
      } 
    }
  },

  created() {
    console.log('激活activated');
    this.getAllCarBrandListData();
    // this.getAllCarSeriesByBrandId();
    // this.getAllCarModelListBySeriesId();
  },

  methods: {

    // 点击搜索
    onSearch() {
      this.selection_model.series_id = '';
      this.selection_model.brand_id = '';
      this.getAllCarModelListBySeriesId();
    },

    // 添加车型
    setPaster(item) {
      console.log(item.model_item_params)
      this.handAccountCanvas.addCarModel(item.model_item_params.objects);
      // 设置成功之后关闭弹窗
      this.handleClose();
    },

    // 点击汽车车系
    handleSeriesItem(itemData) {
      this.selection_model.series_id = itemData.id;
      this.getAllCarModelListBySeriesId();
    },

    // 获取车系里面的所有汽车模型和颜色
    getAllCarModelListBySeriesId() {
      allCarModelListBySeriesId({
        series_id: this.selection_model.series_id,
        model_name: this.selection_model.model_name
      }).then(result => {
        if (result && result.data && result.data.carModelListData && result.data.carModelListData.length > 0) {

          let yearModel = result.data.carModelYearData;
          yearModel.forEach(item => {
            item.listData = result.data.carModelListData.filter(s_item => s_item.model_year === item.model_year);
          });
          this.carModelListData = yearModel;
          this.step = 2;
        } else {
          this.carModelListData = [];
          this.step = 2;
        }
      })
    },

    // 切换车系
    changeCarSeries(index) {
      this.carSeriesTypeIndex = index;
    },

    // 获取全部车系，根据车品牌
    getAllCarSeriesByBrandId() {
      allCarSeriesByBrandId({
        brand_id: this.selection_model.brand_id
      }).then(result => {
        if (result && result.data) {
          let data = result.data;
          let list = [];
          data.forEach(item => {   
            if (item.seriesList && item.seriesList.length > 0) {
              list.push(item);
            }
          })
          this.carSeriesList = list;
          this.step = 1;
        } else {
          this.carSeriesList = [];
          this.step = 1;
        }
      })
    },

    // 点击品牌
    handleBrandItem(itemData) {
      console.log(itemData)
      this.selection_model.brand_id = itemData.id;
      this.getAllCarSeriesByBrandId();
    },

    // 切换品牌字母
    changeBrand(index) {
      this.searchTabIndex  = index;
      if (index === 0) {
        this.searchBrand.is_hot = '1';
        this.searchBrand.brand_letter = '';
      } else {
        this.searchBrand.is_hot = '';
        this.searchBrand.brand_letter = this.brand_letter[index];
      }
      this.getAllCarBrandListData();
    },

    // 获取品牌
    getAllCarBrandListData() {
      allCarBrandListData(this.searchBrand).then(result => {
        if (result && result.data && result.data.length > 0) {
          this.brandListData = result.data;
        } else {
          this.brandListData = [];
        }
      })
    },

    // 点击返回上一步
    handleStep() {
      if (this.selection_model.series_id || this.selection_model.brand_id) {
        this.step = this.step - 1;
      } else {
        this.step = 0;
      }
      this.selection_model.model_name = '';
    },

    // 设置画布背景
    setCanvasBackground(uri) {
      this.handAccountCanvas.setCanvasBackground({
        type: 'img',
        uri,
        isLoad: false
      });
      // 设置成功之后关闭弹窗
      this.handleClose();
    },

    // 关闭弹窗
    handleClose() {
      this.showSelectBackgroundFlag = false;
      this.$emit('onClose', 'background');
    },
  }
};
</script>

<style lang="less" scoped>
  .background-container{
    height: 68vh;
    width: 100vw;
    padding-bottom: 68px;
    display: flex;
    flex-direction: column;

    .header-content{
      width: 100vw;
      // height: 58px;
      position: relative;
      margin-bottom: 12px;

      &::before{
        display: block;
        content: '';
        position: absolute;
        bottom: 0;
        width: 200%;
        left: 0;
        border-bottom: 1px solid #eaeaea;
        transform: scale(0.5);
        transform-origin: left bottom;
      }
    }

    .search-model{
      width: 100%;
      padding: 12px;

      .search-btn{
        color: #fff;
        background: linear-gradient(to right, #8773f9, #1989fa);
        border-radius: 6px;
        padding: 0 12px;
      }

      .van-search__action{
        padding-right: 0;
      }
    }

    .car_brand{
      flex: 1;
      position: relative;
    }

    .series-nav{
      display: flex;
    }

    .back-btn{
      padding-left: 12px;
      padding-right: 12px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-items: center;

      .back-icon{
        width: 26px;
        height: 20px;
        background: linear-gradient(to right, #8773f9, #1989fa);
        display: flex;
        align-items: center;
        justify-items: center;
        border-radius: 4px;
        padding-left: 8px;
      }
    }

    .collapse-content{
      display: flex;

      .model-image{
        width: 80px;
        height: 80px;
        border-radius: 4px;
        background-color: #f5f5f5;
        margin-right: 12px;
      }

      .model-list-item{
        flex: 1;
        display: flex;
        flex-wrap: wrap;

        .list-item{
          width: 36px;
          height: 36px;
          border-radius: 4px;
          border: 1px solid #eaeaea;
          margin-right: 8px;
          position: relative;

          .list-item-name{
            width: 36px;
            height: 16px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 8px;
            position: absolute;
            left: 0;
            bottom: 0;
            background: rgba(000, 000, 000, .7);
            color: #fff;
            border-radius: 2px;
            overflow: hidden; // 超出一行文字自动隐藏
            text-overflow: ellipsis; // 文字隐藏后添加省略号
            white-space: nowrap; // 强制不换行
          }
        }
      }
    }
  }
</style>

<style>
  .background-container .van-tab--active{
    border-color: #8773f9 !important;
    background-color: rgba(135, 115, 249, .1);
  }

  .background-container .van-tabs--line .van-tabs__wrap{
    height: 30px;
  }

  .background-container .brand_item .van-icon__image{
    width: 48px;
    height: 48px;
  }

  .background-container .brand_item .van-grid-item__content--center{
    /* background-color: rgba(31, 33, 41, .8); */
    border-radius: 8px;
  }

  .background-container .brand_item .van-grid-item__text{
    /* color: #fff; */
  }

  .background-container .van-tab__text--ellipsis{
    font-size: 12px;
  }

  .background-container .van-tabs__line{
    display: none;
  }
</style>
